package com.xc.disk.config;

import com.xc.disk.enums.FailCode;
import com.xc.disk.exception.OperateException;
import com.xc.disk.exception.ResultException;
import com.xc.disk.exception.ServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>项目名称: Stars</p>
 * <p>描述: 全局异常处理</p>
 * <P>创建人: 小程</p>
 * <P>创建人邮箱: 779943476@qq.com</p>
 * <p>创建时间: 2019/7/2</p>
 *
 * @version v1.0
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


    /**
     * <p>功能描述: 服务器Exception异常处理 </p>
     * <p>更新人: 小程</p>
     * <p>更新描述: 添加方法</p>
     * <p>更新人邮箱: 779943476@qq.com</p>
     * <p>更新时间: 2019/7/2</p>
     *
     * @return 跨域配置
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultException exception(HttpServletRequest request, Exception e) {
        log.error(e.getMessage(), e);
        ServerException operate = FailCode.SERVER_EXCEPTION.getServerException();
        return new ResultException(operate.getCode(), operate.getMessage());
    }

    /**
     * <p>功能描述: 用户操作异常处理 </p>
     * <p>更新人: 小程</p>
     * <p>更新描述: 添加方法</p>
     * <p>更新人邮箱: 779943476@qq.com</p>
     * <p>更新时间: 2019/7/2</p>
     *
     * @return 跨域配置
     */
    @ExceptionHandler(value = OperateException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultException exception(HttpServletRequest request, OperateException e) {
        log.info("code={},message={}", e.getCode(), e.getMessage());
        return new ResultException(e.getCode(), e.getMessage());
    }

    /**
     * <p>功能描述: 服务器异常 </p>
     * <p>更新人: 小程</p>
     * <p>更新描述: 添加方法</p>
     * <p>更新人邮箱: 779943476@qq.com</p>
     * <p>更新时间: 2019/7/2</p>
     *
     * @return 跨域配置
     */
    @ExceptionHandler(value = ServerException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultException exception(HttpServletRequest request, ServerException e) {
        log.error("code={},message={}", e.getCode(), e.getMessage());
        return new ResultException(e.getCode(), e.getMessage());
    }
}
